const express = require("express");
const router = express.Router();
const path = require("path");
const multer = require("multer");
const upload = multer({ dest: path.join(__dirname, "../../../public/images") });

const { timeTrans } = require("../../../utils");
const {
  getClassify,
  getOneClassify,
  addClassify,
  updateClassify,
  deleteClassify,
  showClassify,
} = require("../../../model/weixin/admin/classify");

/* classify增删改查 */

// 查找classify
router.get("/", async function (req, res, next) {
  let data = await getClassify();
  res.send(data);
});

// 添加classify
router.post("/add", upload.single("classify"), (req, res, next) => {
  const classify_id = Number(req.body.classify_id);

  getOneClassify([classify_id]).then((result) => {
    if (result.length === 0) {
      const src = "http://localhost:3333/images/" + req.body["src[name]"];
      const atime = timeTrans(req.body.atime);
      const title = req.body.title;
      addClassify([classify_id, title, src, atime])
        .then(() => {
          res.send({
            code: 200,
            msg: "添加题库成功",
          });
        })
        .catch((err) => {
          res.send({
            code: 500,
            msg: "添加题库失败",
            err,
          });
        });
    } else {
      res.send({
        code: 500,
        msg: "标识符相同,请重新填写",
      });
    }
  });
});

// 修改classify
router.post("/update", (req, res, next) => {
  console.log(req.body);
  const classify_id = Number(req.body.classify_id);
  const title = req.body.title;

  const src =
    "http://localhost:3333/images/" + req.body["src[name]"] ||
    req.body["src[name]"];
  const atime = timeTrans(req.body.atime);
  updateClassify([title, src, atime, classify_id])
    .then(() => {
      res.send({
        code: 200,
        msg: "修改轮播图片成功",
      });
    })
    .catch((err) => {
      res.send({
        code: 500,
        msg: "修改轮播图片失败",
        err,
      });
    });
});

// 删除单个classify
router.get("/delete", (req, res, next) => {
  const classify_id = Number(req.query.classify_id);
  deleteClassify([classify_id])
    .then(() => {
      res.send({
        code: 200,
        msg: "删除图片成功",
      });
    })
    .catch((err) => {
      res.send({
        code: 500,
        msg: "删除图片失败",
      });
    });
});

// 是否展示classify
router.get("/show", (req, res, next) => {
  // console.log(req.query);
  const isShow = req.query.isShow === "false" ? false : true;
  const classify_id = Number(req.query.classify_id);

  showClassify([isShow, classify_id])
    .then(() => {
      res.send({
        code: 200,
        msg: "修改图片成功",
      });
    })
    .catch((err) => {
      res.send({
        code: 500,
        msg: "修改图片失败",
      });
    });
});

module.exports = router;
